import { getSysParam } from '@api/uc/param'
import { listDeptNode } from '@api/uc/dept'
import { DeptNode } from '@/api/interface'
import { useUserStore } from '@/stores/modules/user'
const sysParams: any = {}
const keys = ['LOGIN_URL', 'PASSWORD_RULE']
export async function init() {
  for (const key of keys) {
    const { data } = await getSysParam(key)
    if (data) {
      sysParams[key] = data
    }
  }
}

export function get(key: string) {
  return sysParams[key]
}

export async function loadParam(key: string) {
  const value = sysParams[key]
  if (value) {
    return value
  }
  const { data } = await getSysParam(key)
  return data
}

export interface TreeNode {
  id: string
  name?: string
  children?: TreeNode[]
  data?: any
}

let deptTree: TreeNode[]
export async function getDeptTree() {
  if (deptTree) {
    return deptTree
  }
  try {
    const store = useUserStore()
    const { data } = await listDeptNode(store.userInfo?.deptId)
    deptTree = list2Tree(data)
    return deptTree
  } catch {
    return deptTree
  }
}

export async function getAllDeptTree() {
  const { data } = await listDeptNode()
  deptTree = list2Tree(data)
  return deptTree
}

export function list2Tree(deptNodes: DeptNode[]) {
  const idMap = new Map<string, TreeNode>()
  const rootChildren = []
  for (let node of deptNodes) {
    const treeNode = {
      id: node.id,
      name: node.name,
      data: node,
      children: []
    }
    idMap.set(node.id, treeNode)
  }

  // 迭代 Map 中的 value
  for (let node of idMap.values()) {
    const parent = idMap.get(node.data?.parentId)
    if (parent) {
      parent.children?.push(node)
    } else {
      rootChildren.push(node)
    }
  }
  return rootChildren
}
